<template>
  <view class="inbound-execute">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">执行入库</block>
    </cu-custom>

    <!-- 头部信息 -->
    <view class="header-section">
      <view class="order-info">
        <text class="order-title">{{
          inboundDetail.inboundNo || "入库单详情"
        }}</text>
        <view class="status-badge" :class="statusClass">
          <text class="status-text">{{ statusText }}</text>
        </view>
      </view>
      <view class="order-details">
        <text class="detail-text"
          >客户名称: {{ inboundDetail.customerName || "-" }}</text
        >
        <text class="detail-text"
          >项目名称: {{ inboundDetail.projectName || "-" }}</text
        >
        <text class="detail-text"
          >计划总数: {{ inboundDetail.totalQuantity || 0 }}套</text
        >
        <text class="detail-text"
          >入库日期: {{ inboundDetail.inboundDate || "-" }}</text
        >
      </view>
    </view>

    <!-- 明细列表 -->
    <view class="detail-section">
      <view class="section-title">
        <text>入库明细</text>
      </view>
      <view class="detail-list">
        <view
          v-for="(item, index) in detailList"
          :key="index"
          class="detail-item"
        >
          <!-- 明细基本信息 -->
          <view class="item-header">
            <view class="window-info">
              <text class="window-series">{{ item.windowSeries }}</text>
              <text class="window-no">{{ item.windowNo }}</text>
            </view>
            <view class="quantity-info">
              <text class="plan-qty"
                >计划: {{ getPlannedQuantity(item) }}套</text
              >
              <text class="actual-qty"
                >已入: {{ item.actualQuantity || 0 }}套</text
              >
              <text class="remaining-qty"
                >待入: {{ getRemainingQuantity(item) }}套</text
              >
            </view>
          </view>

          <!-- 分批次入库区域 -->
          <view class="batch-section">
            <!-- 批次列表 -->
            <view
              v-for="(batch, batchIndex) in item.batches"
              :key="batchIndex"
              class="batch-item"
            >
              <view class="batch-info">
                <text class="batch-label">入库信息</text>
              </view>

              <view class="batch-inputs">
                <!-- 仓库选择 -->
                <view class="field-group">
                  <text class="field-label">仓库</text>
                  <picker
                    :value="batch.warehouseIndex"
                    :range="warehouseList"
                    range-key="warehouseName"
                    @change="onBatchWarehouseChange(index, batchIndex, $event)"
                    class="warehouse-picker"
                  >
                    <view class="picker-display">
                      {{ getWarehouseName(batch.warehouseIndex) }}
                    </view>
                  </picker>
                </view>

                <!-- 库位选择 -->
                <view class="field-group">
                  <text class="field-label">库位</text>
                  <picker
                    :value="batch.locationIndex"
                    :range="getLocationList(batch.warehouseId)"
                    range-key="locationName"
                    @change="onBatchLocationChange(index, batchIndex, $event)"
                    class="location-picker"
                    :disabled="!batch.warehouseId"
                  >
                    <view class="picker-display">
                      {{
                        getLocationName(batch.warehouseId, batch.locationIndex)
                      }}
                    </view>
                  </picker>
                </view>

                <!-- 数量输入 -->
                <view class="field-group">
                  <text class="field-label">数量</text>
                  <input
                    type="number"
                    v-model.number="batch.quantity"
                    @input="onBatchQuantityInput(index, batchIndex, $event)"
                    :placeholder="'请输入数量'"
                  />
                </view>
              </view>
            </view>
          </view>

          <!-- 明细附加信息 -->
          <view class="detail-info">
            <text class="info-text"
              >窗型系列: {{ item.windowSeries || "-" }}</text
            >
            <text class="info-text">门窗编号: {{ item.windowNo || "-" }}</text>
            <text class="info-text"
              >窗型颜色: {{ item.windowColor || "-" }}</text
            >
            <!-- <text class="info-text">批次号: {{ item.batchNo || "-" }}</text> -->
            <text class="info-text"
              >本次入库: {{ getTotalBatchQuantity(item) }}套</text
            >
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-section">
      <view class="summary-info">
        <text class="summary-text"
          >本次入库: {{ getTotalInboundQuantity() }}套</text
        >
      </view>
      <view class="action-buttons">
        <button class="cu-btn bg-gray lg" @click="goBack">取消</button>
        <button
          class="cu-btn bg-blue lg"
          @click="executeInbound"
          :disabled="!canExecuteInbound"
        >
          确认入库
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  getInboundDetail,
  executeInbound as executeInboundApi,
  executeBatchInbound as executeBatchInboundApi,
  getWarehouseList,
  getLocationList,
} from "@/api/wms/finishedGoodsInbound.js";

export default {
  name: "InboundExecute",
  data() {
    return {
      loading: false,
      inboundId: "",
      inboundDetail: {},
      detailList: [],
      warehouseList: [],
      locationList: {},
    };
  },
  computed: {
    statusClass() {
      if (!this.inboundDetail) return "status-pending";
      const statusMap = {
        0: "status-pending",
        1: "status-partial",
        2: "status-completed",
      };
      return statusMap[this.inboundDetail.inboundStatus] || "status-pending";
    },
    statusText() {
      if (!this.inboundDetail) return "待入库";
      const statusMap = {
        0: "待入库",
        1: "部分入库",
        2: "已完成",
      };
      return statusMap[this.inboundDetail.inboundStatus] || "待入库";
    },
    canExecuteInbound() {
      return this.getTotalInboundQuantity() > 0;
    },
  },
  onLoad(options) {
    console.log("onLoad options:", options);
    if (options.id) {
      this.inboundId = options.id;
      this.loadData();
      this.loadWarehouseList();
    } else {
      uni.showToast({
        title: "参数错误",
        icon: "none",
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const response = await getInboundDetail(this.inboundId);
        if (response.data.success) {
          this.inboundDetail = response.data.result;
          this.detailList = (response.data.result.detailList || [])
            .filter((item) => {
              // 过滤掉待入库数量为0的明细（已完全入库）
              const remainingQty =
                (item.plannedQuantity || item.planQuantity || 0) -
                (item.actualQuantity || 0);
              return remainingQty > 0;
            })
            .map((item) => {
              return {
                ...item,
                batches: [
                  {
                    warehouseId: null,
                    warehouseIndex: -1,
                    locationId: null,
                    locationIndex: -1,
                    quantity: 0,
                  },
                ],
              };
            });
        }
      } catch (error) {
        console.error("加载数据失败:", error);
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      } finally {
        this.loading = false;
      }
    },

    async loadWarehouseList() {
      try {
        const response = await getWarehouseList({ warehouseType: 7 });
        if (response.data.success) {
          this.warehouseList = response.data.result || [];
        }
      } catch (error) {
        console.error("加载仓库列表失败:", error);
      }
    },

    async loadLocationList(warehouseId) {
      try {
        const response = await getLocationList(warehouseId);
        if (response.data && response.data.success) {
          return response.data.result || [];
        } else {
          return [];
        }
      } catch (error) {
        console.error("加载库位列表失败:", error);
        uni.showToast({
          title: "加载库位失败",
          icon: "none",
        });
        return [];
      }
    },

    // 获取计划数量
    getPlannedQuantity(item) {
      return item.plannedQuantity || item.planQuantity || 0;
    },

    // 获取剩余待入库数量
    getRemainingQuantity(item) {
      const planned = this.getPlannedQuantity(item);
      const actual = item.actualQuantity || 0;
      return Math.max(0, planned - actual);
    },

    // 获取单个明细的批次总数量
    getTotalBatchQuantity(item) {
      if (!item.batches) return 0;
      return item.batches.reduce((total, batch) => {
        return total + (batch.quantity || 0);
      }, 0);
    },

    // 获取所有明细的入库总数量
    getTotalInboundQuantity() {
      return this.detailList.reduce((total, item) => {
        return total + this.getTotalBatchQuantity(item);
      }, 0);
    },

    // 获取仓库名称
    getWarehouseName(warehouseIndex) {
      if (warehouseIndex >= 0 && this.warehouseList[warehouseIndex]) {
        return this.warehouseList[warehouseIndex].warehouseName;
      }
      return "请选择仓库";
    },

    // 获取库位列表
    getLocationList(warehouseId) {
      const warehouseKey = String(warehouseId);
      return this.locationList[warehouseKey] || [];
    },

    // 获取库位名称
    getLocationName(warehouseId, locationIndex) {
      if (!warehouseId) {
        return "请先选择仓库";
      }
      const locations = this.getLocationList(warehouseId);
      if (locationIndex >= 0 && locations[locationIndex]) {
        return locations[locationIndex].locationName;
      }
      return "请选择库位";
    },

    // 批次仓库选择变更
    async onBatchWarehouseChange(detailIndex, batchIndex, event) {
      const warehouseIndex = event.detail.value;
      const warehouse = this.warehouseList[warehouseIndex];
      const batch = this.detailList[detailIndex].batches[batchIndex];

      batch.warehouseId = warehouse.id;
      batch.warehouseIndex = warehouseIndex;
      batch.locationId = null;
      batch.locationIndex = -1;
      batch.quantity = 0; // 重置数量

      // 加载对应仓库的库位列表
      const locations = await this.loadLocationList(warehouse.id);
      const warehouseKey = String(warehouse.id);
      this.$set(this.locationList, warehouseKey, locations || []);
    },

    // 批次库位选择变更
    onBatchLocationChange(detailIndex, batchIndex, event) {
      const locationIndex = event.detail.value;
      const batch = this.detailList[detailIndex].batches[batchIndex];
      const item = this.detailList[detailIndex];
      const locations = this.getLocationList(batch.warehouseId);
      const location = locations[locationIndex];

      if (location) {
        batch.locationId = location.id;
        batch.locationIndex = locationIndex;

        // 选择库位后，设置数量默认值
        if (batch.warehouseId && batch.locationId && batch.quantity === 0) {
          const remainingQty = this.getRemainingQuantity(item);
          const currentBatchTotal = this.getTotalBatchQuantity(item);
          const availableQty = remainingQty - currentBatchTotal;
          batch.quantity = Math.max(0, availableQty);
        }
      }
    },

    // 批次数量输入变更
    onBatchQuantityInput(detailIndex, batchIndex, event) {
      const value = parseInt(event.detail.value) || 0;
      const item = this.detailList[detailIndex];
      const batch = item.batches[batchIndex];
      const maxQuantity = this.getRemainingQuantity(item);
      const currentTotal =
        this.getTotalBatchQuantity(item) - (batch.quantity || 0);

      if (value > maxQuantity - currentTotal) {
        batch.quantity = maxQuantity - currentTotal;
        uni.showToast({
          title: `最多只能入库${maxQuantity - currentTotal}套`,
          icon: "none",
        });
      } else if (value < 0) {
        batch.quantity = 0;
      } else {
        batch.quantity = value;
      }
    },

    // 增加批次数量
    increaseBatchQuantity(detailIndex, batchIndex) {
      const item = this.detailList[detailIndex];
      const batch = item.batches[batchIndex];
      const maxQuantity = this.getRemainingQuantity(item);
      const currentTotal = this.getTotalBatchQuantity(item);

      if (currentTotal < maxQuantity) {
        batch.quantity = (batch.quantity || 0) + 1;
      }
    },

    // 减少批次数量
    decreaseBatchQuantity(detailIndex, batchIndex) {
      const batch = this.detailList[detailIndex].batches[batchIndex];
      if ((batch.quantity || 0) > 0) {
        batch.quantity = batch.quantity - 1;
      }
    },

    // 执行入库
    async executeInbound() {
      if (!this.canExecuteInbound) {
        uni.showToast({
          title: "请先设置入库信息",
          icon: "none",
        });
        return;
      }

      // 构建入库数据
      const inboundData = {
        inboundId: this.inboundId,
        details: [],
      };

      this.detailList.forEach((item) => {
        item.batches.forEach((batch) => {
          if (batch.quantity > 0 && batch.warehouseId && batch.locationId) {
            inboundData.details.push({
              detailId: item.orderDetailId,
              warehouseId: batch.warehouseId,
              locationId: batch.locationId,
              quantity: batch.quantity,
              windowSeries: item.windowSeries,
              windowNo: item.windowNo,
              windowColor: item.windowColor,
            });
          }
        });
      });

      if (inboundData.details.length === 0) {
        uni.showToast({
          title: "请完善入库信息",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "执行入库中...",
        });

        const response = await executeBatchInboundApi(inboundData);

        if (response.data.success) {
          uni.showToast({
            title: "入库成功",
            icon: "success",
          });

          setTimeout(() => {
            // 通知上一级页面刷新数据
            uni.$emit("inboundExecuted");
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.data.message || "入库失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("执行入库失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style lang="scss" scoped>
.inbound-execute {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 140rpx;
}

.header-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 0 0 20rpx 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(102, 126, 234, 0.3);

  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .order-title {
      font-size: 36rpx;
      font-weight: bold;
      color: white;
    }

    .status-badge {
      padding: 10rpx 20rpx;
      border-radius: 25rpx;
      background: rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(10rpx);
      border: 2rpx solid rgba(255, 255, 255, 0.3);

      .status-text {
        font-size: 26rpx;
        color: white;
        font-weight: 500;
      }
    }
  }

  .order-details {
    .detail-text {
      display: block;
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.9);
      margin-bottom: 12rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.detail-section {
  .section-title {
    background: white;
    padding: 30rpx;
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    border-bottom: 2rpx solid #f0f0f0;
    margin-bottom: 20rpx;
    border-radius: 12rpx 12rpx 0 0;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  }
}

.detail-item {
  background: white;
  margin: 0 20rpx 20rpx 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .item-header {
    padding: 30rpx;
    border-bottom: 2rpx solid #f0f0f0;

    .window-info {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      .window-series {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-right: 20rpx;
        background: linear-gradient(45deg, #667eea, #764ba2);
        background-clip: text;
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }

      .window-no {
        font-size: 28rpx;
        color: #666;
        background: #f0f2f5;
        padding: 6rpx 12rpx;
        border-radius: 8rpx;
      }
    }

    .quantity-info {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      gap: 10rpx;

      .plan-qty,
      .actual-qty,
      .remaining-qty {
        font-size: 24rpx;
        padding: 4rpx 12rpx;
        border-radius: 12rpx;
        background: #f8f9fa;
        color: #666;
      }

      .actual-qty {
        background: #e6f7ff;
        color: #1890ff;
      }

      .remaining-qty {
        background: #fff2e8;
        color: #fa8c16;
        font-weight: bold;
      }
    }
  }
}

.batch-section {
  .batch-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background: #fafafa;

    .batch-title {
      font-size: 28rpx;
      color: #333;
    }

    .add-batch-btn {
      display: flex;
      align-items: center;
      padding: 12rpx 24rpx;
      background: linear-gradient(45deg, #667eea, #764ba2);
      color: white;
      border-radius: 20rpx;
      font-size: 24rpx;
      border: none;
      box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
      transition: all 0.3s ease;

      &:disabled {
        background: #d9d9d9;
        color: #999;
        box-shadow: none;
      }

      &:active:not(:disabled) {
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.4);
      }

      .cuIcon-add {
        margin-right: 10rpx;
        font-size: 20rpx;
      }
    }
  }

  .batch-item {
    border-top: 2rpx solid #f0f0f0;

    .batch-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 30rpx;
      background: #f9f9f9;

      .batch-label {
        font-size: 26rpx;
        color: #333;
        font-weight: bold;
      }

      .remove-batch-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40rpx;
        height: 40rpx;
        background: #ff4d4f;
        color: white;
        border-radius: 50%;
        border: none;
        font-size: 20rpx;
      }
    }

    .batch-inputs {
      padding: 30rpx;

      .field-group {
        display: flex;
        align-items: center;
        margin-bottom: 30rpx;

        .field-label {
          width: 120rpx;
          font-size: 28rpx;
          color: #333;
        }

        .warehouse-picker,
        .location-picker {
          flex: 1;

          .picker-display {
            padding: 20rpx;
            background: #f5f5f5;
            border-radius: 10rpx;
            font-size: 28rpx;
            color: #333;
          }
        }

        .qty-input-field {
          flex: 1;
          padding: 24rpx;
          background: white;
          border: 2rpx solid #e8e8e8;
          border-radius: 12rpx;
          font-size: 28rpx;
          color: #333;
          text-align: center;
          transition: all 0.3s ease;

          &:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
          }

          &::placeholder {
            color: #999;
            font-size: 26rpx;
          }
        }
      }
    }
  }
}

.detail-info {
  padding: 20rpx 30rpx;
  background: #fafafa;

  .info-text {
    display: block;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;

    &:last-child {
      margin-bottom: 0;
      color: #1890ff;
      font-weight: bold;
    }
  }
}

.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 30rpx;
  box-shadow: 0 -8rpx 32rpx rgba(0, 0, 0, 0.12);
  border-radius: 20rpx 20rpx 0 0;

  .summary-info {
    margin-bottom: 24rpx;
    text-align: center;
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #f0f2f5, #e6f7ff);
    border-radius: 16rpx;

    .summary-text {
      font-size: 32rpx;
      color: #1890ff;
      font-weight: bold;
    }
  }

  .action-buttons {
    display: flex;
    gap: 24rpx;

    .cu-btn {
      flex: 1;
      height: 88rpx;
      line-height: 88rpx;
      border-radius: 20rpx;
      font-size: 32rpx;
      border: none;
      font-weight: 600;
      transition: all 0.3s ease;

      &.bg-gray {
        background: #f5f5f5;
        color: #666;
        border: 2rpx solid #e8e8e8;

        &:active {
          background: #e8e8e8;
          transform: translateY(2rpx);
        }
      }

      &.bg-blue {
        background: linear-gradient(45deg, #667eea, #764ba2);
        color: white;
        box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.4);

        &:active:not(:disabled) {
          transform: translateY(2rpx);
          box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.5);
        }

        &:disabled {
          background: #d9d9d9;
          color: #999;
          box-shadow: none;
        }
      }
    }
  }
}
</style>
